/**
 * Copyright (c) 2015-2016, smeooncun 失色 (semooncun@foxmail.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lubiaoqing.jsite.controller.admin;

import java.util.Date;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.StrKit;
import com.lubiaoqing.jsite.interceptor.UserInterceptor;
import com.lubiaoqing.jsite.model.User;
import com.lubiaoqing.jsite.util.CookieUtils;

@Before(UserInterceptor.class)
public class _UserController extends Controller {

	public void index() {
		renderFreeMarker("/WEB-INF/admin/user/user.html");
	}

	@Clear(UserInterceptor.class)
	public void signin() {
		if (this.getSessionAttr("user") == null) {
			createToken("csrf");
			renderFreeMarker("/WEB-INF/admin/login.html");
			return;
		} else {
			redirect("/admin");
		}
	}
	
	public void signout() {
		removeSessionAttr("user");
		CookieUtils.remove(this, "user");
		redirect("/admin/user/signin.html");
	}

	@Clear(UserInterceptor.class)
	public void dosignin() {
		if (validateToken("csrf")) {
			String username = getPara("username");
			String password = getPara("password");
			setAttr("username", username);
			setAttr("password", password);
			if (StrKit.isBlank(password) || StrKit.isBlank(username)) {
				setAttr("error", 1);
				setAttr("msg", "帐号和密码不能为空！");
				createToken("csrf");
				renderFreeMarker("/WEB-INF/admin/login.html");
				return;
			} else {
				User user = User.dao
						.findFirst(
								"select id,username from user where username=? and password=? and status=1",
								username, HashKit.md5(password));
				if (user != null) {
					user.set("logged", new Date()).update();
					setSessionAttr("user", user);
					CookieUtils.put(this, "user",
							String.valueOf(user.getLong("id")));
					redirect("/admin");
				} else {
					setAttr("error", 1);
					setAttr("msg", "帐号或密码错误，请重试！");
					createToken("csrf");
					renderFreeMarker("/WEB-INF/admin/login.html");
					return;
				}
			}
		} else {
			createToken("csrf");
			setAttr("error", 1);
			setAttr("msg", "验证未通过，请刷新后重试！");
			renderFreeMarker("/WEB-INF/admin/login.html");
		}
	}
}
